<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="auto">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              v-model="formData.customerId"
              :disabled="formData.customerDefault"
              class="w-1/1"
              filterable
              placeholder="请选择客户"
              @change="handleCustomerChange(formData.customerId)"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="运营经理" prop="managerName">
            <el-input readonly v-model="managerName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="营业状态" prop="runningStatus">
            <el-input readonly v-model="businessStatus" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="电气方案图纸资料" name="projectElectric">
        <ProjectElectricForm ref="projectElectricFormRef" :project-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="能源报装类别" name="projectEnergy">
        <ProjectEnergyForm ref="projectEnergyFormRef" :project-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="废气治理方案图纸资料" name="projectGas">
        <ProjectGasForm ref="projectGasFormRef" :project-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="废水管道图纸资料" name="projectPipeline">
        <ProjectPipelineForm ref="projectPipelineFormRef" :project-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="生产线建设现状" name="projectProduction">
        <ProjectProductionForm ref="projectProductionFormRef" :project-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="车间生产线图纸资料" name="projectWorkshop">
        <ProjectWorkshopForm ref="projectWorkshopFormRef" :project-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="其他工程方案图纸资料" name="projectOther">
        <ProjectOtherForm ref="projectOtherFormRef" :project-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="项目验收资料" name="projectCheck">
        <ProjectCheckForm ref="projectCheckFormRef" :project-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as CustomerApi from '@/api/crm/customer'
import { DICT_TYPE, getDictObj } from '@/utils/dict'
import { ProjectApi, ProjectVO } from '@/api/crm/project'
import ProjectElectricForm from './components/ProjectElectricForm.vue'
import ProjectEnergyForm from './components/ProjectEnergyForm.vue'
import ProjectGasForm from './components/ProjectGasForm.vue'
import ProjectOtherForm from './components/ProjectOtherForm.vue'
import ProjectPipelineForm from './components/ProjectPipelineForm.vue'
import ProjectProductionForm from './components/ProjectProductionForm.vue'
import ProjectWorkshopForm from './components/ProjectWorkshopForm.vue'
import ProjectCheckForm from './components/ProjectCheckForm.vue'

/** CRM 企业项目信息 表单 */
defineOptions({ name: 'ProjectForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const customerList = ref([]) // 客户列表的数据
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerId: undefined as unknown as number,
  precursorChemicals: undefined,
  explosiveChemicals: undefined,
  toxicChemicals: undefined,
  customerDefault: false,
})
const formRules = reactive({
  customerId: [{ required: true, message: '客户id不能为空', trigger: 'blur' }],
  precursorChemicals: [
    { required: true, message: '易制毒化学品使用申报不能为空', trigger: 'change' }
  ],
  explosiveChemicals: [
    { required: true, message: '易制爆化学品使用申报不能为空', trigger: 'change' }
  ],
  toxicChemicals: [{ required: true, message: '剧毒化学品使用申报不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const managerName = ref() // 运营经理
const businessStatus = ref() // 营业状态

const handleCustomerChange = async (customerId: number) => {
  if (!customerId) {
    managerName.value = ''
    businessStatus.value = ''
    return
  }
  const customer = customerList.value.find<CustomerApi.CustomerVO>((item) => item.id === customerId)
  managerName.value = customer?.ownerUserName
  const businessStatusObj = getDictObj(DICT_TYPE.CRM_BUSINESS_STATUS, customer?.businessStatus)
  businessStatus.value = businessStatusObj?.label ?? ''
}

/** 子表的表单 */
const subTabsName = ref('projectElectric')
const projectElectricFormRef = ref()
const projectEnergyFormRef = ref()
const projectGasFormRef = ref()
const projectOtherFormRef = ref()
const projectPipelineFormRef = ref()
const projectProductionFormRef = ref()
const projectWorkshopFormRef = ref()
const projectCheckFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id || customerId) {
    formLoading.value = true
    try {
      if (id) {
        formData.value = await ProjectApi.getProject(id)
        formData.value.customerDefault = true // 默认客户的选择，不允许变
      } else {
        formData.value.customerId = customerId
        formData.value.customerDefault = true // 默认客户的选择，不允许变
      }
      const res = await CustomerApi.getCustomer(customerId ?? formData.value.customerId)
      managerName.value = res.ownerUserName
      businessStatus.value =
        getDictObj(DICT_TYPE.CRM_BUSINESS_STATUS, res.businessStatus)?.label ?? ''
    } finally {
      formLoading.value = false
    }
  }
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await projectElectricFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'projectElectric'
    return
  }
  try {
    await projectEnergyFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'projectEnergy'
    return
  }
  try {
    await projectGasFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'projectGas'
    return
  }
  try {
    await projectOtherFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'projectOther'
    return
  }
  try {
    await projectPipelineFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'projectPipeline'
    return
  }
  try {
    await projectProductionFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'projectProduction'
    return
  }
  try {
    await projectWorkshopFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'projectWorkshop'
    return
  }try {
    await projectCheckFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'projectCheck'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProjectVO
    // 拼接子表的数据
    data.projectElectrics = projectElectricFormRef.value.getData()
    data.projectEnergys = projectEnergyFormRef.value.getData()
    data.projectGass = projectGasFormRef.value.getData()
    data.projectOthers = projectOtherFormRef.value.getData()
    data.projectPipelines = projectPipelineFormRef.value.getData()
    data.projectProductions = projectProductionFormRef.value.getData()
    data.projectWorkshops = projectWorkshopFormRef.value.getData()
    data.projectChecks = projectCheckFormRef.value.getData()
    if (formType.value === 'create') {
      await ProjectApi.createProject(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProjectApi.updateProject(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined as unknown as number,
    precursorChemicals: undefined,
    explosiveChemicals: undefined,
    toxicChemicals: undefined,
    customerDefault: false,
  }
  managerName.value = ''
  businessStatus.value = ''
  formRef.value?.resetFields()
}
</script>
